package com.acme.domain.email.service;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;

public class EmailService {

	private static Queue<Email> queue = new Queue<Email>();
	private static EmailService instance;

	private EmailService(final Email email) {
		new Thread(new Runnable() {
			public void run(){
				while (!queue.isClosed()){
					sendNotificationEmail(email);						
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
						return;
					}
				}
				System.out.println("input thread finished");
			}
		}).start();
		
		new Thread(new Runnable(){
			public void run() {
				while (!queue.isEmpty() || !queue.isClosed()){
					try {
						queue.getEmail();
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
						return;
					}
				}
				System.out.println("output thread finished");
			}
			
		}).start();
		
	}
	
	public static EmailService getEmailService(Email email) {
		if (instance == null){
			instance = new EmailService(email);
		}
		return instance;
	}
	
	public void sendNotificationEmail(Email email){
		try {
			queue.addEmail(email);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void close() {
		System.out.println("Closed!");
		queue.close();
	}
}